package com.aries.crossgate.modules.sys.controller;

import com.aries.crossgate.common.log.config.Log;
import com.aries.crossgate.common.utils.Constant;
import com.aries.crossgate.common.utils.MD5Utils;
import com.aries.crossgate.common.utils.R;
import com.aries.crossgate.common.utils.ShiroUtils;
import com.aries.crossgate.common.base.BaseController;
import com.aries.crossgate.modules.sys.entity.SysUser;
import com.aries.crossgate.modules.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * TODO: 登录
 * @author 李贝留斯
 * @email sunyadongsyd@163.com
 * @date 2018/4/24 14:42
 */
@Controller
public class SysLoginController extends BaseController {
	
	@Autowired
	private SysUserService sysUserService;

	/**
	 * TODO: 登录
	 * @author 李贝留斯
	 * @param
	 * @date 2018/5/04 15:20
	 */
	@Log("登录页")
	@GetMapping(value = "/login.html")
	public ModelAndView login(){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("login");
		return modelAndView;
	}

	/**
	 * TODO: 登录
	 * @author 李贝留斯
	 * @param
	 * @date 2018/5/04 15:20
	 */
	@Log("登陆")
	@ResponseBody
	@PostMapping(value = "/login.html")
	public R tologin(SysUser sysUser){
        SysUser user = sysUserService.getByUserName(sysUser.getUserName());
        String passWord = MD5Utils.encrypt(sysUser.getUserName(), sysUser.getPassWord());

        if(user == null || !user.getPassWord().equals(passWord)) {
            return R.error("用户名或密码错误");
        }

        if(user.getStatus() == 0) {
            return R.error("账号已被锁定,请联系管理员");
        }
		UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), passWord);
        Subject subject = ShiroUtils.getSubject();
        try {
            subject.login(token);
            return R.ok(Constant.SUCCESS);//sysUserService.saveUserToken(user.getUserId());
        } catch (AuthenticationException e) {
            return R.error("用户名或密码错误");
        }
	}

	/**
	 * TODO: 
	 * @author 李贝留斯
	 * @email sunyadongsyd@163.com
	 * @date 2018/5/15 10:26
	 */
	@Log("注销")
	@RequestMapping(value="/logout.html")
	public ModelAndView logout(){
		ModelAndView mv = new ModelAndView();

		//shiro管理的session
		Session session = ShiroUtils.getSession();
		session.removeAttribute(Constant.SYSUSER);
		//shiro销毁登录
		Subject subject = SecurityUtils.getSubject();
		subject.logout();

		mv.setViewName("redirect:login");
		return mv;
	}
}
